package com.yunbao.core.springmvc;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * <p>序列化LocalDateTime</p>
 *
 * @author 安能
 * @date 2019年9月18日03:04:18
 */
//@Configuration
public class LocalDateTimeSerializerConfig {


    @Value("${spring.jackson.date-format}")
    private String pattern;




    /**
     * 接收前端datetime参数
     *
     * @return
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConvert() {
        return source -> {

            DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
            LocalDateTime date = null;
            try {
                date = LocalDateTime.parse(source, df);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return date;
        };
    }


    @Bean
    public LocalDateTimeSerializer localDateTimeDeserializer() {

        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }

}